<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/11/14
 * Time: 17:10
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class WarehouseShelf extends BaseModel
{
    protected $pk = 'shelf_id';

    protected $insert = ['create_by'];

    /**
     * 可分配
     * @var int
     */
    const STATUS_ASS = 0;

    /**
     * 被占用
     * @var int
     */
    const STATUS_USED = 10;

    /**
     * 已放满
     * @var int
     */
    const STATUS_FULL = 20;

    /**
     * 可回收
     * @var int
     */
    const STATUS_WAIT_TRASH = 30;

    /**
     * 已回收
     * @var int
     */
    const STATUS_SUCC_TRASH = 40;

    public static $STATUS = [
        self::STATUS_ASS        => '可分配',
        self::STATUS_USED       => '被占用',
        self::STATUS_FULL       => '已放满',
        self::STATUS_WAIT_TRASH => '可回收',
        self::STATUS_SUCC_TRASH => '已回收',
    ];

    protected function getStatusAttr($value)
    {
        return isset(self::$STATUS[$value]) ? self::$STATUS[$value] : $value;
    }

    /**
     * 关联仓库
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function warehouse()
    {
        return $this->belongsTo(Warehouse::class);
    }

    /**
     * 关联区域
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function area()
    {
        return $this->belongsTo(WarehouseArea::class, 'area_id', 'area_id');
    }

    /**
     * 货架编码是否存在
     * @param string $code 货架编码
     * @param int $warehouseId 仓库
     * @return bool
     * @date 2021/02/18
     * @author longli
     */
    public static function hasCode($code, $warehouseId = 0)
    {
        $location = static::where('code', trim($code));
        if(!empty($warehouseId)) $location->where('warehouse_id', intval($warehouseId));
        return !!$location->count();
    }

    /**
     * 获取仓库货架
     * @param int $wid 仓库 id
     * @param int $aid 区域 id
     * @return WarehouseShelf[]
     * @date 2021/02/21
     * @author longli
     */
    public static function getShelf($wid, $aid = 0)
    {
        $shelf = static::where('warehouse_id', $wid);
        if(!empty($aid)) $shelf->where('area_id', $aid);
        return $shelf->select();
    }

    /**
     * 生成货架编号
     * @param string $prefix 前缀
     * @return string
     * @date 2021/02/18
     * @author longli
     */
    public static function generateCode($prefix = '', $len = 8)
    {
        do
        {
            $rand = \app\common\library\Tools::getRandStr($len, 2);
            $code = $prefix . strtoupper($rand);
        }while(static::hasCode($code));
        return $code;
    }
}
